package com.wthink.hzgj.sdcard.viewmodel

import android.annotation.SuppressLint
import android.os.StatFs
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wthink.hzgj.BusApplication
import com.wthink.hzgj.data.Result
import com.wthink.hzgj.data.domain.Storage
import com.wthink.hzgj.sdcard.Upandata
import com.wthink.hzgj.service.DevService
import com.wthink.hzgj.util.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.DecimalFormat

@SuppressLint("NewApi")
class SdcardViewmodel : ViewModel() {

    val sdcardSiz = MutableLiveData("")
    val nandSiz = MutableLiveData("")
    //val storage = MutableLiveData(Storage("","","",""))
    val storage = MutableLiveData(Upandata("",""))

    fun start(){
        val sdcardSize = String.format(
            "%s/%s",
            getFormatGB(getSDAvailableSize("/mnt/sdcard")),
            getFormatGB(getSDTotalSize("/mnt/sdcard"))
        )
        sdcardSiz.postValue(sdcardSize)

        val nandSize = String.format(
            "%s/%s",
            getFormatGB(getSDAvailableSize("/mnt/internal_sd")),
            getFormatGB(getSDTotalSize("/mnt/internal_sd"))
        )
        nandSiz.postValue(nandSize)

        queryStorage()

        }

        private fun queryStorage() {
            viewModelScope.launch(Dispatchers.IO) {
                val result = DevService.queryStorage()
                if (result is Result.Success) {
                    val data = result.data
                    val upan = String.format(
                        "%s/%s",
                        getFormatBusGB(data.udisk_free.toLong()),
                        getFormatBusGB(data.udisk_total.toLong())
                    )
                    val buspan = String.format(
                        "%s/%s",
                        getFormatBusGB(data.hdisk_free.toLong()),
                        getFormatBusGB(data.hdisk_total.toLong())
                    )
                    storage.postValue(Upandata(upan, buspan))
                }
            }
        }

    /**
     *
     * 获得SD卡总大小
     * @return
     */
    private fun getSDTotalSize(`val`: String): Long {
        var blockSize: Long = 0
        var totalBlocks: Long = 0
        val path = File(`val`)
        if (path.canRead() && path.canWrite()) {
            val stat = StatFs(path.path)
            blockSize = stat.blockSizeLong
            totalBlocks = stat.blockCountLong
        }
        return blockSize * totalBlocks / (1024 * 1024)
    }

    /**
     * 获得sd卡剩余容量，即可用大小
     * @return
     */
    private fun getSDAvailableSize(`val`: String): Long {
        var blockSize: Long = 0
        var availableBlocks: Long = 0
        val path = File(`val`)
        if (path.canRead() && path.canWrite()) {
            val stat = StatFs(path.path)
            blockSize = stat.blockSizeLong
            availableBlocks = stat.availableBlocksLong
        }
        return blockSize * availableBlocks / (1024 * 1024)
    }

    /**
     * 得到格式化的容量，已GB为单位
     * @param size 已MB为单位，要格式化的数据
     * @return
     */
    fun getFormatGB(size: Long): String? {
        val d = size / 1024.00
        val df = DecimalFormat("#.0")
        var s = df.format(d)
        if (s.startsWith(".")) {
            s = "0$s"
        }
        return s + "GB"
    }

    fun getFormatBusGB(size: Long): String? {
        val d = size / 1024.00 / 1024.00 /1024.00
        val df = DecimalFormat("#.0")
        var s = df.format(d)
        if (s.startsWith(".")) {
            s = "0$s"
        }
        return s + "GB"
    }
}